import React, {forwardRef, useEffect, useImperativeHandle, useState} from 'react';
import {EditorState, convertToRaw} from 'draft-js';
import {Editor} from 'react-draft-wysiwyg';
import draftToHtml from 'draftjs-to-html'
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css'
import htmlToDraft from 'html-to-draftjs';
import ContentState from 'draft-js/lib/ContentState';

/**
 * 新增商品的富文本编辑器
 * @returns {JSX.Element}
 * @constructor
 */
function RichTextEditor(props,ref){
  const [editorState,setEditorState] = useState(EditorState.createEmpty());

  /**
   * 实时改动editorState
   * @param editorState
   */
  function onEditorStateChange(editorState){
    setEditorState(editorState);
  }

  useEffect(function(){
    const {detail} = props;
    if(detail){ // 如果有值, 根据html格式字符串创建一个对应的编辑对象
      const contentBlock = htmlToDraft(detail);
      const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
      const editorState = EditorState.createWithContent(contentState);
      // 创建一个没有内容的编辑对象
      setEditorState(editorState);
    }else{
      // 创建一个没有内容的编辑对象
      setEditorState(EditorState.createEmpty());
    }
  },[]);

  // 暴露给父组件的方法
  useImperativeHandle(ref,()=>({
    getDetail: ()=>{
      return draftToHtml(convertToRaw(editorState.getCurrentContent()));
    }
  }))

  return (
    <Editor
      editorState={editorState}
      onEditorStateChange={onEditorStateChange}
      editorStyle={{border: '1px solid black',minHeight: 200,paddingLeft: 10,paddingRight: 10}}
    />
  );
}

RichTextEditor = forwardRef(RichTextEditor);
export default RichTextEditor;